/* edited by liubin */

#include "apue_error.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdarg.h>

static void pr_error( int errno_flag, const char *fmt, va_list ap );

void err_dump( const char *fmt, ... )
{
	va_list ap;

	va_start( ap, fmt );
	pr_error( 1, fmt, ap );
	va_end( ap );
	abort();    /* dump core and terminate */
	exit( 1 );    /* should't get here */
}

void err_msg( const char *fmt, ... )
{
	va_list ap;

	va_start( ap, fmt );
	pr_error( 0, fmt, ap );
	va_end( ap );
	return;
}

void err_quit( const char *fmt, ... )
{
	va_list ap;

	va_start( ap, fmt );
	pr_error( 0, fmt, ap );
	va_end( ap );
	exit( 1 );
}

void err_sys( const char *fmt, ... )
{
	va_list ap;

	va_start( ap, fmt );
	pr_error( 1, fmt, ap );
	va_end( ap );
	exit( 1 );
}

void err_ret( const char *fmt, ... )
{
	va_list ap;

	va_start( ap, fmt );
	pr_error( 1, fmt, ap );
	va_end( ap );
	return;
}

/* this function never set errno */
void pr_error( int errno_flag, const char *fmt, va_list ap )
{
	/* TODO use buffer */
	int errno_save = errno;

	vfprintf( stderr, fmt, ap );
	if( errno_flag ) {  /* TODO: use strerror_r to be thread safe */
		fprintf( stderr, ": %s", strerror( errno_save ) );
	}
	fprintf( stderr, "\n" );
	fflush( stderr );
	errno = errno_save;
}
